package leetcode_题库;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/27 13:15 星期六
 */
public class _102_二叉树的层序遍历 {
    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);

        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;

        List<List<Integer>> nn = levelOrder(n1);
        System.err.println(nn);
    }

    /**
     * 广度优先解法
     * > 2022/08/27 16:58:18
     * 解答成功:
     * 	执行耗时:1 ms,击败了57.90% 的Java用户
     * 	内存消耗:41.5 MB,击败了51.20% 的Java用户
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root==null){
            return list;
        }
        //队列
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        //若队列不为空，继续
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> floor = new ArrayList<>();
            //当前行包含的size数
            for (int i = 0; i < size; i++) {
                TreeNode n = queue.poll();
                floor.add(n.val);
                //存入左右
                if (n.left != null) {
                    queue.add(n.left);
                }
                if (n.right != null) {
                    queue.add(n.right);
                }
            }
            //一行结束
            list.add(floor);
        }
        return list;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
